var $ = getApp().globalData.eui;
$.page({

    /**
     * 页面的初始数据
     */
    data: {
        vwidth: 1,
        vheight: 1,
        id: 0,
        product: null,
        curUser: null,
        canvasid: "myCanvas",
        cansubmit: false,
        showSharePic: true,
        shareImage: "",
        productid: 0,
        productQr: "", //产品码
        miniQr: "", //小程序码
        haibaoWidth: 0,
        haibaoHeight: 0,
        ShapeType: {
            TEXT: 0,
            IMAGE: 1,
            MINIQR: 2
        }
        //文本绑定：["不绑定","用户昵称", "会员id", "产品名称", "产品简介", "产品卖价", "产品市场价","产品优惠价"]
        //图片绑定：["不绑定", "用户头像", "产品主图"]
        //小程序码：["小程序码", "产品码"]
    },

    /**
     * 生命周期函数--监听页面加载
     * options参数：
     * id: 模板ID
     * productid:产品ID
     */
    onLoad: function (options) {
        var me = this;
        var templid = $.toInt(options.id);
        me.data.productid = $.toInt(options.productid);

        setTimeout(function () {
            $.api("mall."+(me.data.productid?'HaibaoTempl':'DistHaibaoTempl')+".Load", {
                    "id": templid
                })
                .then(function (value) {
                    //
                    var oHaibao = $.fromJson(value.design);
                    var entities = oHaibao.shapes;
                    me.setData({
                        "haibaoWidth": $.toInt(oHaibao.width),
                        "haibaoHeight": $.toInt(oHaibao.height)
                    });

                    $.log("海报宽度：" + oHaibao.width + " 高度：" + oHaibao.height);

                    $.log("after download templ");
                    wx.showLoading({
                        title: '正在生成海报...',
                    });
                    me.fnDownloadHaibao(oHaibao, entities, function () {
                        $.log("after download all images....");
                        me.drawHaibao(oHaibao, entities, function () {
                            wx.hideLoading()
                        },function () {
                            wx.hideLoading()
                        })
                    }, function (err) {
                        wx.hideLoading()
                        $.errorBox("错误", err.message);
                    });
                })
        }, 1200);

    },
    fnDownloadImage: function (url, fnOK, fnFail) {
        $.log("下载图片：" + url);
        wx.getImageInfo({
            src: url,
            success: function (res) {
                fnOK(res);
            },
            fail: function (err) {
                if ($.isFunction(fnFail)) {
                    fnFail(err);
                }
            }
        })
    },
    fnDownloadHaibao: function (oHaibao, entities, fnOK, fnFail) {
        var me = this;
        $.log("enter fnDownloadImg");
        var ShapeType = me.data.ShapeType;

        var fn = function (entities, index, fnOK, fnFail) {
            $.log("downloading...." + index);
            var fnGetUrl = function (entity, url, index, fnFail) {
                $.log("fnGetUrl:" + url);
                if (url) {
                    if (url.indexOf("/") === 0) {
                        url = $.getConfig("server_url") + url;
                    }
                    me.fnDownloadImage(url, function (res) {
                        entity.$width = res.width;
                        entity.$height = res.height;
                        entity.$path = res.path;
                        $.log("after download image url:" + url + " path:" + res.path);
                        fn(entities, index + 1, fnOK, fnFail)
                    }, function (err) {
                        $.log("fail " + err.message);
                        if ($.isFunction(fnFail)) {
                            fnFail(err);
                        }
                    })
                } else {
                    fn(entities, index + 1, fnOK, fnFail)
                }
            };
            if (index < entities.length) {
                var entity = entities[index];

                if (entity.type === ShapeType.IMAGE) {

                    switch ($.toInt(entity.bindtype)) {
                        case 0:
                            fnGetUrl(entity, entity.url, index, fnFail);
                            break;
                        case 1: //用户头像

                            me.fnGetUser(function (user) {

                                fnGetUrl(entity, user.icon, index, fnFail);
                            }, fnFail)
                            break;
                        case 2: //产品主图
                            me.fnGetProduct(function (product) {
                                if (product && product.sku) {
                                    fnGetUrl(entity, product.sku.icon, index, fnFail);
                                }
                            }, fnFail)
                            break;
                        default:
                            fnGetUrl(entity, "", index, fnFail);
                            break;
                    }

                } else if (entity.type === ShapeType.MINIQR) {
                    switch ($.toInt(entity.qrtype)) {
                        case 0: //小程序码
                            me.fnGetMiniQrCode(function (qr) {
                                fnGetUrl(entity, qr, index, fnFail)
                            }, fnFail);
                            break;
                        case 1: //产品码
                            me.fnGetProductQrCode(function (qr) {
                                fnGetUrl(entity, qr, index, fnFail)
                            }, fnFail)
                            break;
                        default:
                            fn(entities, index + 1, fnOK, fnFail)
                            break;
                    }
                } else if (entity.type === ShapeType.TEXT) {
                    switch ($.toInt(entity.bindtype)) {
                        case 0: //不绑定
                            fn(entities, index + 1, fnOK, fnFail)
                            break;
                        case 1: //用户昵称
                            me.fnGetUser(function (user) {
                                entity.text = user.alias;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail)
                            break;
                        case 2: //会员id
                            me.fnGetUser(function (user) {
                                entity.text = user.sn;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail)
                            break;
                        case 3: //产品名称
                            me.fnGetProduct(function (product) {
                                if (product) entity.text = product.name;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail);
                            break;
                        case 4: //产品简介
                            me.fnGetProduct(function (product) {
                                if (product) entity.text = product.intro;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail);
                            break;
                        case 5: //产品卖价
                            me.fnGetProduct(function (product) {
                                if (product && product.sku) entity.text = "￥"+product.sku.saleprice;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail);
                            break;
                        case 6: //产品市场价
                            me.fnGetProduct(function (product) {
                                if (product && product.sku) entity.text = "￥"+product.sku.marketprice;
                                entity.isstrikeout=true;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail);
                            break;
                        case 7: //产品优惠价
                            me.fnGetProduct(function (product) {
                                if (product && product.sku) entity.text = "￥"+product.sku.vipprice;
                                fn(entities, index + 1, fnOK, fnFail)
                            }, fnFail);
                            break;
                        default:
                            fn(entities, index + 1, fnOK, fnFail)
                            break;
                    }
                } else {
                    fn(entities, index + 1, fnOK, fnFail)
                }
            } else {
                fnOK(entities);
            }
        };
        if (oHaibao.bgimg) {
            var bgimgSrc = oHaibao.bgimg;
            if (!(bgimgSrc.indexOf("http:") === 0 || bgimgSrc.indexOf("https:") === 0)) {
                bgimgSrc = $.getConfig("server_url") + bgimgSrc;
            }
            me.fnDownloadImage(bgimgSrc, function (res) {
                oHaibao.$bgimg = res.path;
                oHaibao.$bgimgWidth = res.width;
                oHaibao.$bgimgHeight = res.height;
                fn(entities, 0, fnOK, fnFail);
            }, fnFail);
        } else {
            fn(entities, 0, fnOK, fnFail);
        }

    },
    drawHaibao: function (oHaibao, entities, fnOK,fnFail) {
        var me = this;
        var width = $.toInt(oHaibao.width);
        var height = $.toInt(oHaibao.height);

        var canvasID = me.data.canvasid;

        const canvasCtx = wx.createCanvasContext(canvasID);

        $.log("准备画海报");

        //画背景
        if (oHaibao.bgimg) {
            canvasCtx.drawImage(oHaibao.$bgimg,
                0, 0, oHaibao.$bgimgWidth, oHaibao.$bgimgHeight,
                0, 0, oHaibao.width, oHaibao.height
            );
        } else if (oHaibao.bgcolor) {
            canvasCtx.setFillStyle(oHaibao.bgcolor);
            canvasCtx.fillRect(0, 0, width, height);
        }


        var drawText = function (ctx, str,halign, fontsize, x, y, width) {
            if (!str) return;

            halign = $.toInt(halign);
            var top = y;
            var lineWidth = 0;
            var lastSubStrIndex = 0; //每次开始截取的字符串的索引 
            var left = 0;
            for (let i = 0; i < str.length; i++) {
                lineWidth += ctx.measureText(str[i]).width;
                if (lineWidth > width) {
                    if (halign === 0) left = x;
                    else if (halign === 1) left = x + width / 2 - lineWidth / 2;
                    else if (halign === 2) left = x + width - lineWidth;
                    ctx.fillText(str.substring(lastSubStrIndex, i), left, top); //绘制截取部分                
                    top += fontsize + 3;
                    lineWidth = 0;
                    lastSubStrIndex = i;
                }
                if (i == str.length - 1) { //绘制剩余部分 
                    lineWidth = ctx.measureText(str.substring(lastSubStrIndex, i + 1)).width;
                    if (halign === 0) left = x;
                    else if (halign === 1) left = x + width / 2 - lineWidth / 2;
                    else if (halign === 2) left = x + width - lineWidth;
                    ctx.fillText(str.substring(lastSubStrIndex, i + 1), left, top);
                }
            }

        };

        var ShapeType = me.data.ShapeType;

        $.each(entities, function (entity) {
            if (entity.type === ShapeType.TEXT) {
                var text = entity.text;

                var fontsize = $.toInt(entity.fontsize);

                if (entity.fontcolor) {
                    var fontcolor = entity.fontcolor.replace(/ /g, '');
                    canvasCtx.setFillStyle(fontcolor);
                } else {
                    canvasCtx.setFillStyle('black');
                }

                var font = "";
                font += (entity.isitalic ? 'italic' : 'normal');
                font += " ";
                font += (entity.isbold ? 'bold' : 'normal');
                font += " ";
                font += "" + fontsize + "px";
                font += " ";
                if (entity.fontname) font += entity.fontname;
                else font += "宋体";

                if (font) canvasCtx.font = font;

                var position = entity.position;
                drawText(canvasCtx, text, $.toInt(entity.halign),fontsize, position.x, position.y, position.width);

                if( entity.isstrikeout ){
                    var skwidth = canvasCtx.measureText(text).width;
                    var dy = -fontsize/2+2;

                    $.log("--->fontsize:"+fontsize+" dy:"+dy);
                    canvasCtx.moveTo(position.x, position.y+dy);
                    canvasCtx.lineTo(position.x+skwidth, position.y+dy);
                    canvasCtx.setStrokeStyle(entity.fontcolor?entity.fontcolor:'grey');
                    canvasCtx.stroke()
                }

                canvasCtx.stroke();
            } else if (entity.type === ShapeType.IMAGE) {
                $.log("draw image:" + entity.$path);
                if (entity.$path) {
                    var imagePos = entity.position;
                    if (entity.isrounded) {
                        canvasCtx.save();
                        canvasCtx.beginPath(); //开始绘制
                        canvasCtx.arc(imagePos.x+imagePos.width/2,imagePos.y+imagePos.width/2, imagePos.width/2, 0, Math.PI * 2, false);
                        canvasCtx.clip();
                        canvasCtx.drawImage(entity.$path,
                            0, 0, entity.$width, entity.$height,
                            imagePos.x, imagePos.y, imagePos.width, imagePos.width
                        );
                        canvasCtx.restore();

                    } else {
                        canvasCtx.drawImage(entity.$path,
                            0, 0, entity.$width, entity.$height,
                            imagePos.x, imagePos.y, imagePos.width, imagePos.height
                        );
                    }

                }

            } else if (entity.type === ShapeType.MINIQR) {
                if (entity.$path) {
                    var imagePos = entity.position;
                    if (entity.isrounded) {
                        canvasCtx.save();
                        canvasCtx.beginPath(); //开始绘制
                        canvasCtx.arc(imagePos.x+imagePos.width/2,imagePos.y+imagePos.width/2, imagePos.width/2, 0, Math.PI * 2, false);
                        canvasCtx.clip();
                        canvasCtx.drawImage(entity.$path,
                            0, 0, entity.$width, entity.$height,
                            imagePos.x, imagePos.y, imagePos.width, imagePos.width
                        );
                        canvasCtx.restore();
                    } else {
                        canvasCtx.drawImage(entity.$path,
                            0, 0, entity.$width, entity.$height,
                            imagePos.x, imagePos.y, imagePos.width, imagePos.width //以宽度为准的圆形
                        );
                    }
                    
                }
            }
        });

        //保存到相册
        var fnSave = function () {
            wx.saveImageToPhotosAlbum({
                filePath: me.data.shareImage,
                success:function(res) {
                    $.log("图片已保存到相册，赶紧晒一下吧~");
                    fnOK();
                    wx.showModal({
                        content: '图片已保存到相册，赶紧晒一下吧~',
                        showCancel: false,
                        confirmText: '好哒',
                        confirmColor: '#72B9C3',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            }
                            $.back();

                        },
                        fail:function () {
                            if( $.isFunction(fnFail)){
                                fnFail();
                            }
                        }
                    });
                },
                fail:function () {
                    if( $.isFunction(fnFail)){
                        fnFail();
                    }
                }
            });
        };

        $.log("---- before canvas.draw");
        canvasCtx.draw(false, function () {
            $.log("after draw----");
            setTimeout(function () {
                $.log("--- before canvasToTempFilePath");
                wx.canvasToTempFilePath({
                    canvasId: canvasID,
                    success: function (res) {
                        $.log("after canvasToTempFilePath---------");
                        setTimeout(function () {
                            var tempFilePath = res.tempFilePath;
                            console.log("生成的图片临时目录：" + tempFilePath);
                            me.setData({
                                shareImage: tempFilePath,
                                showSharePic: false
                                // canvasHidden:true
                            });
                            wx.hideToast();

                            wx.previewImage({
                                current: tempFilePath, // 当前显示图片的http链接
                                urls: [tempFilePath] // 需要预览的图片http链接列表
                            });

                            $.isAuthed("scope.writePhotosAlbum").then(function (isAuthed) {
                                if (!isAuthed) {
                                    wx.authorize({
                                        scope: 'scope.writePhotosAlbum',
                                        success: function (res) {
                                            fnSave();
                                        },
                                        fail:function () {
                                            if( $.isFunction(fnFail)){
                                                fnFail();
                                            }
                                        }
                                    });
                                } else {
                                    fnSave();
                                }
                            })
                        }, 2000);
                    },
                    fail: function (res) {
                        $.log("==>failed to canvasToTempFilePath:" + $.toJson(res));
                        if( $.isFunction(fnFail)){
                            fnFail();
                        }
                        console.log(res);
                        wx.hideToast();
                    }
                })
            }, 200);
        });
    },
    fnGetProduct: function (fnOK, fnFail) {
        var me = this;
        if (me.data.product) fnOK(me.data.product);
        else {
            if (me.data.productid) {
                var product = null;
                $.api("mall.Product.Load", {
                        "id": me.data.productid
                    })
                    .then(function (value) {
                        product = value;
                        product.usedist = $.toInt(product.usedist);
                        $.api("mall.Product.LoadSkus", {
                                "id": me.data.productid
                            })
                            .then(function (value) {
                                var sku = null;
                                //只需要价格最低的那个sku
                                var price = 0;
                                $.each(value, function (s) {
                                    var p = $.toFloat(s.saleprice);
                                    if (price == 0) {
                                        sku = s;
                                        price = p;
                                    } else {
                                        if (p < price) {
                                            sku = s;
                                            price = p;
                                        }
                                    }
                                })
                                product.sku = sku;
                                me.data.product = product;
                                fnOK(product);
                            }, function (err) {
                                if ($.isFunction(fnFail)) fnFail(err);
                            })
                    }, function (err) {
                        if ($.isFunction(fnFail)) fnFail(err);
                    })
            } else {
                fnOK(null);
            }
        }

    },
    fnGetUser: function (fnOK, fnFail) {
        var me = this;
        if (me.data.curUser) {
            fnOK(me.data.curUser);
        } else {
            $.api($.getConfig("apiLoadCur", {}))
                .then(function (value) {
                    me.data.curUser = value;
                    $.log("after getuser....");
                    fnOK(value);
                }, function (err) {
                    $.log("fail to getuser:" + err.message);
                    if ($.isFunction(fnFail)) fnFail(err)
                })
        }

    },
    //得到小程序码
    fnGetMiniQrCode: function (fnOK, fnFail) {
        var me = this;
        if (me.data.miniQr) fnOK(me.data.miniQr);
        else {
            var id = 0;
            var path = "pages/index";
            $.api("mall.Product.GetMiniFileDist", {
                    "id": id,
                    "path": path
                })
                .then(function (value) {
                    me.data.miniQr = value;
                    fnOK(value);
                }, function (err) {
                    if ($.isFunction(fnFail)) fnFail(err);
                })
        }
    },
    //得到产品码
    fnGetProductQrCode: function (fnOK, fnFail) {
        var me = this;
        if (me.data.productQr) fnOK(me.data.productQr);
        else {
            me.fnGetProduct(function (oProduct) {
                if (oProduct) {
                    var useDist = $.toInt(oProduct.usedist);
                    var id = oProduct.id;
                    var path = "pages/product/detail";
                    $.api("mall.Product." + (useDist ? 'GetMiniFileDist' : 'GetMiniFile'), {
                            "id": id,
                            "path": path
                        })
                        .then(function (value) {
                            me.data.productQr = value;
                            fnOK(value);
                        }, function (err) {
                            if ($.isFunction(fnFail)) fnFail(err);
                        })
                } else {
                    fnOK("");
                }
            }, fnFail);
        }

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})